<?php

namespace app\api\controller\mall;

use app\admin\model\mall\Shipper;
use app\api\library\KdApiExpOrder;
use app\api\model\mall\Area;
use app\api\model\mall\Carts;
use app\api\model\mall\Order as OrderModel;
use app\api\model\mall\Address;

use app\api\model\mall\OrderAction;
use app\api\model\mall\OrderAftersales;
use app\api\model\mall\OrderGoods;
//use addons\shop\library\KdApiExpOrder;
use app\api\model\Pay;
use app\common\controller\Api;
use app\common\model\User;
use think\Db;
use think\Log;

/**
 * 订单接口
 */
class Order extends Api
{
    protected $noNeedLogin = ['epay'];
    protected $noNeedRight = ['*'];

    //计算邮费，判断商品
    public function carts()
    {
        //$config = get_addon_config('shop');
        $cart_ids = $this->request->post('ids');
        $address_id = $this->request->post('address_id/d'); //地址id
        if (empty($cart_ids)) {
            $this->error('参数缺失');
        }
        $user_coupon_id = $this->request->post('user_coupon_id/d'); //优惠券
        $address = Address::get($address_id);
        $orderInfo = [
            'order_sn'    => '',
            'amount'      => 0, //订单金额（包含运费）
            'shippingfee' => 0, //运费
            'goodsprice'  => 0 //商品金额
        ];
        $goodsList = [];
        $area_id = !empty($address) ? $address->area_id : 0;
        try {
            list($orderItem, $goodsList) = OrderModel::computeCarts($orderInfo, $cart_ids, $this->auth->id, $area_id, $user_coupon_id);
            if (empty($goodsList)) {
                throw new \Exception("未找到商品");
            }
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        foreach ($goodsList as $item) {
            $item->category_id = $item->goods->category_id;
            //$item->brand_id = $item->goods->brand_id;
            $item->goods->visible(explode(',', 'id,title,image,price,marketprice,is_upgrade'));
        }
        //获取我的可以使用的优惠券
        //$goods_ids = array_column($goodsList, 'goods_id');
        //$category_ids = array_column($goodsList, 'category_id');
        //$brand_ids = array_column($goodsList, 'brand_id');
        $this->success('获取成功', [
            //'coupons'          => UserCoupon::myGoodsCoupon($this->auth->id, $goods_ids, $category_ids, $brand_ids),
            'goods_list'       => $goodsList,
            'order_info'       => $orderInfo,
            'address'          => $address
            //'couponTotalPrice' => floatval(!isset($config['shippingfeecoupon']) || $config['shippingfeecoupon'] == 0 ? $orderInfo['goodsprice'] : $orderInfo['amount'])
        ]);
    }

    //提交订单
    public function add()
    {
        $cart_ids = $this->request->post('ids');
        $address_id = $this->request->post('address_id/d'); //地址id
        $user_coupon_id = $this->request->post('user_coupon_id/d'); //地址id
        $memo = $this->request->post('memo');
        if (empty($address_id)) {
            $this->error('请选择地址');
        }
        if (empty($cart_ids)) {
            $this->error('请选择商品');
        }
        //为购物车id
        //校验购物车id 合法
        $row = (new Carts)->where('id', 'IN', $cart_ids)->where('user_id', '<>', $this->auth->id)->find();
        if ($row) {
            $this->error('存在不合法购物车数据');
        }
        $order = null;
        try {
            $order = OrderModel::createOrder($address_id, $this->auth->id, $cart_ids, $user_coupon_id, $memo);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('下单成功！', $order);
    }

    public function getAreainfoAttr( $data)
    {
        $result = [
            'province' => null,
            'city'     => null,
            'area'     => null,
        ];
        $areaList = Area::where('id', 'in', [$data['province_id'], $data['city_id'], $data['area_id']])->select();
        foreach ($areaList as $index => $item) {
            $levelName = ($item['level'] == 1 ? 'province' : ($item['level'] == 2 ? 'city' : 'area'));
            $result[$levelName] = $item;
        }
        return $result;
    }
    //订单详情
    public function detail()
    {
        $order_sn = $this->request->param('order_sn');
        if (empty($order_sn)) {
            $this->error('参数缺失');
        }
        $order = OrderModel::getDetail($order_sn, $this->auth->id);
        if (empty($order)) {
            $this->error('未找到订单');
        }
        $order->append(['status_text']);
        $order->hidden(explode(',', 'method,transactionid,updatetime,deletetime'));
        $order->expiretime = $order->expiretime - time();

        $areainfo = $this->getAreainfoAttr($order);

        $order->province = $areainfo['province'] ? $areainfo['province']['name'] : '';
        $order->city = $areainfo['city'] ? $areainfo['city']['name'] : '';
        $order->area = $areainfo['area'] ? $areainfo['area']['name'] : '';
        $this->success('', $order);
    }

    //订单列表
    public function index()
    {
        $param = $this->request->param();
        $param['user_id'] = $this->auth->id;
        $list = OrderModel::tableList($param);
        foreach ($list as $item) {
            $item->append(['status_text']);
            $field = 'id,order_sn,amount,expressno,expressname,saleamount,shippingfee,paystate,orderstate,shippingstate,order_goods,status,status_text,expiretime,order_type';
            $item->visible(explode(',', $field));
        }
        foreach ($list as $k=>$v){

            $list[$k]['expiretime'] = $v['expiretime'] - time();
        }
        $this->success('获取成功', $list);
    }

    //取消订单
    public function cancel()
    {
        $order_sn = input('order_sn','');
        if (!$order_sn) {
            $this->error('参数错误');
        }
        $order = OrderModel::getByOrderSn($order_sn);
        if (empty($order)) {
            $this->error('订单不存在');
        }
        if ($order->user_id != $this->auth->id) {
            $this->error('不能越权操作');
        }
        if ($order->status == 'hidden') {
            $this->error('订单已失效！');
        }

        //可以取消
        if (!$order->orderstate) {
            // 启动事务
            Db::startTrans();
            try {
                $order->orderstate = 1;
                $order->canceltime = time();
                $order->save();
                foreach ($order->order_goods as $item) {
                    $sku = $item->sku;
                    $goods = $item->goods;
                    //商品库存恢复
                    if ($sku) {
                        $sku->setInc('stocks', $item->nums);
                    }
                    if ($goods) {
                        $goods->setInc('stocks', $item->nums);
                    }
                }
                if ($order->paystate==1){
                    \app\admin\model\mall\Order::refund($order->order_sn, $order->paytype, $order->saleamount);
                    //User::score($order->saleamount,$order->user_id,'订单取消退款,编号:'.$order->order_sn);
                }
                //恢复优惠券
                //UserCoupon::resetUserCoupon($order->user_coupon_id, $order->order_sn);
                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error('订单取消失败');
            }
            //记录操作
            OrderAction::push($order->order_sn, '系统', '订单取消成功');
            $this->success('订单取消成功！', $order['status']);
        } else {
            $this->error('订单不允许取消');
        }
    }

    //删除订单
    public function del()
    {
        $order_sn = input('order_sn','');
        if (!$order_sn) {
            $this->error('参数错误');
        }
        $order = OrderModel::get(['order_sn'=>$order_sn]);
        if (empty($order)) {
            $this->error('订单不存在');
        }
        if ($order->user_id != $this->auth->id) {
            $this->error('不能越权操作');
        }
        if ($order->orderstate==1&&$order->orderstate==2){
            if ($order->delete()){
                $this->success('删除成功');
            } else {
                $this->error('删除失败');
            }

        } else {
            $this->error('订单不允许删除');
        }
    }

    public function taskoverdue()
    {
        $id = input('id','');
        if (!$id) {
            $this->error('参数错误');
        }
        //$order = OrderModel::getByOrderSn($order_sn);
        $order = \app\api\model\mall\Order::get($id);
        if (empty($order)) {
            $this->error('订单不存在');
        }

        if ($order->status == 'hidden') {
            $this->error('订单已失效！');
        }

        //订单过期
        if (!$order->orderstate) {
            // 启动事务
            Db::startTrans();
            try {
                $order->save(['orderstate' => 2]);
                //库存恢复
                OrderGoods::setGoodsStocksInc($order->order_sn);
                //恢复优惠券
                //UserCoupon::resetUserCoupon($orderInfo->user_coupon_id, $orderInfo->order_sn);
                // 提交事务
                Db::commit();

            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success("请求成功");
        }
    }


    //订单支付
    public function pay()
    {
        $order_sn = $this->request->post('order_sn');
        $paytype = $this->request->post('paytype');
        $method = $this->request->post('method','miniapp');
        $appid = $this->request->post('appid'); //为APP的应用id
        $returnurl = $this->request->post('returnurl', '', 'trim');
        $openid = $this->auth->wechat_open_id;

        //非H5 支付,非余额
        /*if (in_array($method, ['miniapp', 'mp']) && $paytype == 'wechat') {

            $openid = $this->auth->wechat_open_id;

        }*/

        //$orderInfo = OrderModel::getByOrderSn($order_sn);
        $orderInfo = \app\api\model\mall\Order::get(['order_sn'=>$order_sn]);
        if (!$orderInfo) {
            $this->error("未找到指定的订单");
        }
        if ($orderInfo['paystate']) {
            $this->error("订单已经支付，请勿重复支付");
        }
        //订单过期
        if (!$orderInfo['orderstate'] && time() > $orderInfo['expiretime']) {
            // 启动事务
            Db::startTrans();
            try {
                $orderInfo->save(['orderstate' => 2]);
                //库存恢复
                OrderGoods::setGoodsStocksInc($orderInfo->order_sn);
                //恢复优惠券
                //UserCoupon::resetUserCoupon($orderInfo->user_coupon_id, $orderInfo->order_sn);
                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
            }
            $this->error("订单已失效");
        }
        $response = null;
        try {
            $request = \think\Request::instance();
            $notice_url = $request->root(true) . '/api/mall/order/epay';
            //$response = \app\api\model\shop\ShopOrder::pay($order_no, $this->auth->id, $paytype, $method, $openid, '', $returnurl);
            //$pay_model = new Pay();
            //$response = $pay_model->unipay($orderInfo['order_no'],$orderInfo['goods_name'],$paytype,$orderInfo['order_price'],$notice_url);

            $response = OrderModel::pay($order_sn, $this->auth->id, $paytype, $method, $openid, '', $returnurl);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success("请求成功", $response);
    }

    //确认收货
    public function takedelivery()
    {
        $order_sn = $this->request->post('order_sn');
        if (!$order_sn) {
            $this->error('参数错误');
        }
        $order = OrderModel::getByOrderSn($order_sn);
        if (empty($order)) {
            $this->error('订单不存在');
        }
        if ($order->user_id != $this->auth->id) {
            $this->error('不能越权操作');
        }
        if ($order->status == 'hidden') {
            $this->error('订单已失效！');
        }
        if ($order->paystate == 1 && !$order->orderstate && $order->shippingstate == 1) {
            $order->shippingstate = 2;
            $order->receivetime = time();
            $order->orderstate = 3;
            $order->save();
            //记录操作
            OrderAction::push($order->order_sn, '系统', '订单确认收货成功');
            $this->success('确认收货成功');
        }
        $this->error('未可确认收货');
    }

    //查询物流
    public function logistics()
    {
        $order_sn = $this->request->param('order_sn');
        if (empty($order_sn)) {
            $this->error('参数缺失');
        }

        $order = OrderModel::getDetail($order_sn, $this->auth->id);

        if (empty($order)) {
            $this->error('未找到订单');
        }

        if (!$order->shippingstate) {
            $this->error('订单未发货');
        }
        /*$electronics = Db::name('shop_order_electronics')->where('order_sn', $order_sn)->where('status', 0)->find();
        if (!$electronics) {
            $this->error('订单未发货');
        }*/
        $shipper= Shipper::get(['name'=>$order['expressname']]);
        $result = KdApiExpOrder::getLogisticsQuery([
            'order_sn'      => $order_sn,
            'logistic_code' => $order['expressno'],
            'shipper_code'  => $shipper['shipper_code']
        ]);

        if ($result['Success']) {
            $this->success('查询成功', $result['Traces']);
        }
        $this->error('查询失败');
    }


    //订单数量
    public function num()
    {
        //待付款
        $wait_pay = \app\admin\model\mall\Order::where(['user_id'=>$this->auth->id,'orderstate'=>0,'paystate'=>0])->count();
        //待发货
        $wait_send = \app\admin\model\mall\Order::where(['user_id'=>$this->auth->id,'orderstate'=>0,'paystate'=>1,'shippingstate'=>0])->count();
        //待收货
        $wait_receive = \app\admin\model\mall\Order::where(['user_id'=>$this->auth->id,'shippingstate'=>1])->count();
        $refund = OrderAftersales::where(['user_id'=>$this->auth->id,'status'=>1])->count();
        $data = [
            'wait_pay'=>$wait_pay,
            'wait_send'=>$wait_send,
            'wait_receive'=>$wait_receive,
            'refund'=>$refund
        ];
        $this->success('', $data);
    }


    /**
     * @ DateTime 2021-06-01
     * @ 支付回调
     * @return void
     */
    public function epay()
    {
        $type = $this->request->param('type');
        $paytype = $this->request->param('paytype');
        if ($type == 'notify') {
            $pay = \addons\epay\library\Service::checkNotify($paytype);
            if (!$pay) {
                echo '签名错误';
                return;
            }
            $data = $pay->verify();
            try {
                $payamount = $paytype == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;
                \app\api\model\mall\Order::settle($data['out_trade_no'], $payamount, $paytype == 'alipay' ? $data['trade_no'] : $data['transaction_id']);
            } catch (\Exception $e) {
                \think\Log::write($e->getMessage(), 'epay');
            }
            echo $pay->success();
        }
        return;
    }

    /**
     * @ DateTime 2021-06-01
     * @ 支付回调
     * @return void
     */
//    public function epay()
//    {
//        $data = input();
//        Log::error('自营商城回调'.json_encode($data,320));
//        try {
//            $order_no = input('order_no','');
//            $trans_status = input('trans_status');//0订单 1成功 2撤消 3退款
//            $trans_oktime =input('trans_oktime','');//支付完成时间
//            $total_fee = input('total_fee',0);//付款金额
//            $trans_type = input('trans_type','');//支付类型 wxpay alipay unionpay
//            $transaction_id = input('transaction_id','');
//            if ($trans_status==1){
//                \app\api\model\mall\Order::settle($order_no, $total_fee, $trans_type,$trans_oktime,$transaction_id);
//            }
//
//            //$payamount = $paytype == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;
//            //\app\api\model\mall\Order::settle($data['out_trade_no'], $payamount, $paytype == 'alipay' ? $data['trade_no'] : $data['transaction_id']);
//        } catch (\Exception $e) {
//            \think\Log::write($e->getMessage(), 'epay');
//        }
//        $this->success();
//
//    }
}
